import { Component, EventEmitter, Injector, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { NameValue, TaxomonyItemNext, TaxonomyFrontItem, TaxonomyItemLevel1Dto, TaxonomyServiceProxy } from '@shared/service-proxies/service-proxies';
import { forEach as _forEach } from 'lodash-es';



export const enum TaxonomyComboOption {
    getTaxonomyItemLevel1 = '0',
    getTaxonomyLevelNext = '1'
}


@Component({
    selector: 'taxonomy-combo',
    template:
    `<select  *ngIf="!multiple" class="form-control edited" name="{{fieldName}}" id="{{fieldName}}"  
    [(ngModel)]="selectedValue" (change)="callBackOrNull($event)" >
        <option *ngFor="let item of taxonomys" [value]="item.value">{{item.name}}</option>
    </select>
    <p-multiSelect (onClick)="multiSelectChanged($event)" styleClass="form-control" *ngIf="multiple" [options]="taxonomys" [(ngModel)]="pMutiSelectedValue" 
      [defaultLabel]="defaultLabel" optionLabel="name" [showToggleAll]="false"></p-multiSelect>
`
})
export class TaxonomyComboComponent extends AppComponentBase implements OnInit ,OnChanges{
    @Input() fieldName: string;
    @Input() typeId: string;
    @Input() multiple: boolean = false;
    @Input() defaultValue: string;
    @Input() byValue: boolean;

    @Input() selectedValue: string;
    @Output() selectedValueChange = new EventEmitter<string>();

    //p-multiSelect 的值
    pMutiSelectedValue:NameValue[] = [];

    @Input() relateVal: string;

    @Output() callBack = new EventEmitter<any>();

    taxonomys: NameValue[] = [];

    private Isinit= true;
    defaultLabel ='';

    constructor(
        private _taxonomyService: TaxonomyServiceProxy,
        injector: Injector) {
        super(injector);
    }

    ngOnInit(): void {
        this.defaultLabel = this.l("UnSelect");

        if (!this.typeId) {
            this.taxonomys = [];
            this.tryAddEmptyItem();
            return;
        }

        const splits = this.typeId.split('|');
        this.taxonomys = [];

        if (splits.length === 1) {
            //如果是多级数据，会拉取树状选项
            this._taxonomyService.getTaxonomyCollections(splits[0]).subscribe(result => {
                let maxLevel = result.filter(t=> t.level > 0);
                if(maxLevel.length > 0){
                    result.forEach(item => {
                        item.displayName = Array(item.level + 1).join('---') + ' ' + item.displayName;
                    });
                }
                this.taxonomys = this.TaxonomyDataToOptionData(result);
                this.tryAddEmptyItem();
            });
        } else if (splits.length === 2) {
            if(splits[1] === TaxonomyComboOption.getTaxonomyLevelNext){
                this._taxonomyService.getTaxonomyLevelNext(splits[0]).subscribe(result => {
                    this.taxonomys = this.TaxonomyDataToOptionData(result);
                    this.tryAddEmptyItem();
                });
            }else{
                //不取下层数据
                this._taxonomyService.getTaxonomyItemLevel1(splits[0]).subscribe(result => {
                    this.taxonomys = this.TaxonomyDataToOptionData(result);
                    this.tryAddEmptyItem();
                });
            }
        }
    }


    ngOnChanges(changes: SimpleChanges): void {
        if (changes['relateVal']) {
             if(this.relateVal){
                 let preId = this.relateVal;
                 if(!preId){
                    this.taxonomys = [];
                    this.selectedValue = '';
                    this.tryAddEmptyItem();
                    this.callBackOrNull(null);
                    return;
                }
                 this._taxonomyService.getTaxonomyLevelNext(preId).subscribe(result => {
                    this.taxonomys = this.TaxonomyDataToOptionData(result);
                    if(!this.Isinit){
                        this.selectedValue = '';   
                    }else{
                        this.Isinit = false;
                    }
                    this.tryAddEmptyItem();
                });
             }
        }
    }

    callBackOrNull(e:any) {
        this.selectedValueChange.emit(this.selectedValue);
        
        if (this.callBack) {
            setTimeout(() => {
                this.callBack.emit();
            }, 300);
        }
    }

    multiSelectChanged(e:any){
        //{originalEvent: event.originalEvent, value: this.value, itemValue: optionValue}
        this.selectedValue = this.pMutiSelectedValue.map(t=> t.value).join(',');
        this.callBackOrNull(null);
    }

    private InitSelectValue(){
        if(this.selectedValue){
            let dataArr =  this.selectedValue.split(',');
            var filtered = [];
            dataArr.forEach(tt => {
                if(tt){
                    filtered.push(tt);
                }
            });
            this.pMutiSelectedValue = this.taxonomys.filter(t=> filtered.findIndex(tt => tt === t.value) >=0 )
        }
    }

    private TaxonomyDataToOptionData(result:TaxonomyFrontItem[] | TaxomonyItemNext[] | TaxonomyItemLevel1Dto[]):NameValue[] {
        if(this.byValue){
            return result.map(t=> new NameValue({name :t.displayName,value: t.value}));
        }else{
            return result.map(t=> new NameValue({name :t.displayName,value: t.id}));
        }
    }

    private tryAddEmptyItem(){
        if(this.defaultValue === "#"){
            let item = new NameValue({value:'',name: this.l("EmptyOnes")});
            // if(this.byValue){
            //     item.value = '00000000-0000-0000-0000-000000000000';
            // }
            this.taxonomys.unshift(item);
        }
        if (this.multiple){
            this.InitSelectValue();
        }
        // 如果没有选中项，而又没有默认值，则自动选中第一项
        if (!this.selectedValue && !this.multiple) {
            if (this.taxonomys.length > 0) {
                this.selectedValue = this.taxonomys[0].value;
                this.callBackOrNull(null);
            }
        }
    }
}
